package com.shop.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author XCH
 * @date 2025 - 05 - 28
 */
public class FileUtils {
    private static final String FTP_SERVER = "8.134.184.130";
    private static final int FTP_PORT = 21;
    private static final String FTP_USERNAME = "test";
    private static final String FTP_PASSWORD = "xiaochenghao";
    private static final String FTP_REMOTE_DIR = "/www/wwwroot/images/";
    private static final int FTP_CONNECTION_TIMEOUT = 20000; // 20秒连接超时
    private static final int FTP_DATA_TIMEOUT = 180000; // 180秒数据传输超时

    public String uploadFile(MultipartFile file) {
        System.out.println("开始上传文件");
        System.out.println("文件名: " + file.getOriginalFilename());
        System.out.println("文件大小: " + file.getSize() + " 字节");

        if (file.isEmpty()) {
            return "上传文件为空";
        }

        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.setConnectTimeout(FTP_CONNECTION_TIMEOUT);
            ftpClient.setDataTimeout(FTP_DATA_TIMEOUT);

            // 连接FTP服务器
            System.out.println("尝试连接FTP服务器: " + FTP_SERVER);
            ftpClient.connect(FTP_SERVER, FTP_PORT);

            // 检查FTP响应
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.out.println("FTP服务器拒绝连接，响应码: " + reply);
                return "FTP服务器拒绝连接";
            }

            // 登录
            boolean loginSuccess = ftpClient.login(FTP_USERNAME, FTP_PASSWORD);
            System.out.println("FTP登录结果: " + loginSuccess);

            if (!loginSuccess) {
                System.out.println("FTP登录失败: " + ftpClient.getReplyString());
                return "FTP登录失败";
            }

            // 设置文件类型和模式
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.setControlKeepAliveTimeout(800); // 设置控制连接保持活动超时（秒）

            // 使用主动模式
//            System.out.println("使用主动模式");
//            ftpClient.enterLocalActiveMode();

            // 使用被动模式
            ftpClient.enterLocalPassiveMode(); // 添加这行

            // 设置缓冲区大小
            ftpClient.setBufferSize(1024 * 1024); // 1MB缓冲区

            // 检查并创建目录
            boolean dirExists = ftpClient.changeWorkingDirectory(FTP_REMOTE_DIR);
            System.out.println("目录存在: " + dirExists);

            if (!dirExists) {
                // 创建多级目录
                String[] dirs = FTP_REMOTE_DIR.split("/");
                String tempPath = "";
                for (String dir : dirs) {
                    if (dir.isEmpty()) continue;
                    tempPath += "/" + dir;
                    try {
                        ftpClient.changeWorkingDirectory(tempPath);
                    } catch (Exception e) {
                        ftpClient.makeDirectory(tempPath);
                        ftpClient.changeWorkingDirectory(tempPath);
                    }
                }
            }

            // 生成唯一文件名，避免覆盖
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + extension;

            // 直接从MultipartFile获取输入流上传
            try (InputStream inputStream = file.getInputStream()) {
                System.out.println("开始上传文件到FTP...");
                boolean success = ftpClient.storeFile(newFilename, inputStream);

                System.out.println("文件上传结果: " + success);
                if (success) {
                    //返回访问地址
                    System.out.println("文件上传成功。文件名为：" + newFilename);
                    return "http://8.134.184.130/" + newFilename;
                } else {
                    return "文件上传失败: " + ftpClient.getReplyString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败，错误信息: " + e.getMessage();
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.logout();
                    ftpClient.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public String uploadFiles(MultipartFile[] files) {
        System.out.println("开始上传文件");
        if (files == null || files.length == 0) {
            return "[]";
        }

        List<String> urlList = new ArrayList<>();

        for (MultipartFile file : files) {
            String url = uploadFile(file);
            // 只添加成功上传的文件URL（不包含错误信息）
            if (url.startsWith("http")) {
                urlList.add(url);
            }
        }

        // 构建数组格式字符串，不包含双引号
        StringBuilder jsonArray = new StringBuilder("[");
        for (int i = 0; i < urlList.size(); i++) {
            jsonArray.append(urlList.get(i));
            if (i < urlList.size() - 1) {
                jsonArray.append(", ");
            }
        }
        jsonArray.append("]");


        return jsonArray.toString();
    }

}
